package rlyy.framework.netty.server;

import org.springframework.beans.BeanInstantiationException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.boot.web.server.WebServer;
import org.springframework.stereotype.Component;
import rlyy.framework.core.servlet.InitServletContextServer;
import rlyy.framework.netty.config.ServerConfig;

import java.lang.reflect.Constructor;

/**
 * 初始化NettyServer
 *
 * @author yuanqinglong
 * @since 2021/4/13 9:22
 */
@Component
public class InitNettyServer implements InstantiationAwareBeanPostProcessor {


    @Autowired
    private ServerConfig serverConfig;

    /**
     * Bean实例化之前调用
     * 手动实例化InitServletContextServer，构造传递NettyServer服务，保住不会被重复赋值
     *
     * @param beanClass class
     * @param beanName  名称
     * @return null
     * @throws BeansException 异常
     */
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if (InitServletContextServer.class.isAssignableFrom(beanClass)) {
            try {
                Constructor<?> constructor = beanClass.getConstructor(WebServer.class);
                return constructor.newInstance(new NettyServer(serverConfig));
            } catch (Exception e) {
                throw new BeanInstantiationException(beanClass, "InitServletContextServer实例化异常", e);
            }
        }
        return null;
    }

}
